//
//  UIView+Ext.swift
//  TimMusic
//
//  Created by nkl on 2024/10/14.
//

import Foundation

extension UIView {
    var width: CGFloat {
        get {
            return frame.size.width
        }
        set {
            var f = frame
            f.size.width = newValue
            frame = f
        }
    }

    var height: CGFloat {
        set {
            var f = frame
            f.size.height = newValue
            frame = f
        }
        get {
            return frame.size.height
        }
    }

    var x: CGFloat {
        set {
            var f = frame
            f.origin.x = newValue
            frame = f
        }
        get {
            return frame.origin.x
        }
    }

    var y: CGFloat {
        set {
            var f = frame
            f.origin.y = newValue
            frame = f
        }
        get {
            return frame.origin.y
        }
    }

    var centerX: CGFloat {
        set {
            var c = center
            c.x = newValue
            center = c
        }
        get {
            return center.x
        }
    }

    // 部分圆角（必须Frame已知）
    func makeCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = path.cgPath
        layer.mask = maskLayer
    }

    func setGradient(colors: [UIColor], index: Int? = nil) {
        let colors = colors.map({ $0.cgColor })

        // 创建渐变图层并添加到视图上
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = CGPoint(x: 0, y: 0) // 起始点位置
        gradientLayer.endPoint = CGPoint(x: 0, y: 1) // 结束点位置
        gradientLayer.frame = bounds
        if let index = index {
            layer.insertSublayer(gradientLayer, at: UInt32(index))
        } else {
            layer.addSublayer(gradientLayer)
        }
    }

    func setGradient(colors: [UIColor], index: Int? = nil, start: CGPoint, end: CGPoint) {
        let colors = colors.map({ $0.cgColor })

        // 创建渐变图层并添加到视图上
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = start // 起始点位置
        gradientLayer.endPoint = end // 结束点位置
        gradientLayer.frame = bounds
        if let index = index {
            layer.insertSublayer(gradientLayer, at: UInt32(index))
        } else {
            layer.addSublayer(gradientLayer)
        }
    }
}
